package com.example

import com.example.data.DatabaseFactory
import com.example.plugins.configureHTTP
import com.example.plugins.configureRouting
import com.example.plugins.configureSecurity
import com.example.plugins.configureSerialization
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.request.*
import java.text.SimpleDateFormat

fun main() {
    embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module)
        .start(wait = true)
}

//const val BASE_IMAGE_URL = "http://10.0.2.2:8080/api/cover/"
val tSimpleDateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm")

fun Application.module() {
    install(createApplicationPlugin("123") {
        onCallRespond { call, body ->
            transformBody {
                println("method:${call.request.httpMethod}")
                call.response.headers.apply {
                    if (call.request.httpMethod == HttpMethod.Options) append(
                        "Access-Control-Allow-Origin",
                        "http://localhost:8081"
                    )
                    append("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT,PATCH")
                    append("Access-Control-Allow-Headers", "*")
                    append("Access-Control-Allow-Credentials", "true")
                }
                if (call.request.httpMethod == HttpMethod.Options) HttpStatusCode.OK else it
            }
        }
    })
    DatabaseFactory.init()
    configureSecurity()
    configureHTTP()
    configureSerialization()
    configureRouting()

}
